import Vue from "vue";
import VueRouter from "vue-router";
const Login = () => import("views/Login");
const Layout = () => import("../views/layout/index.vue");
// const Users = () => import("../views/users");
// const Roles = () => import("../views/roles");
import store from "./../store";
import * as types from "../store/mutations-types";

Vue.use(VueRouter);

// 解决重复点击导航报错
const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}
const routes = [
  // {
  //   path:'',
  //   redirect:'/users'
  // },
  {
    path: "",
    name: "Layout",
    component: Layout,
    meta: {
      requiresAuth: true,
      name: "首页"
    },
    children: [// 登录后 作为动态路由 动态传入 
      // {
      //   path: "users",
      //   name: "users",
      //   component: Users
      // },
      // {
      //   path: "roles",
      //   name: "roles",
      //   component: Roles
      // }
    ]
  },
  {
    path: "/login",
    name: "login",
    component: Login
  },
];

const router = new VueRouter({
  mode: "hash",
  base: process.env.BASE_URL,
  routes
});

// router.beforeEach((to, from, next) => {
//   if (to.matched.some(record => record.meta.requiresAuth)) {
//     if (!auth.loggedIn()) {
//       next({
//         path: '/login',
//         query: { redirect: to.fullPath }
//       })
//     } else {
//       next()
//     }
//   } else {
//     next() // 确保一定要调用 next()
//   }
// })

router.beforeEach((to, from, next) => {
  if (to.path == "/login") return next();
  //获取token
  const tokenStr = sessionStorage.getItem("token") || store.state.token;
  if (!tokenStr) return next("/login");
  if(router.getRoutes().length<3){
    store.dispatch(types.MENUS_ACTION) //登录成功后到达 layout 页面 开始提交 获取菜单的action请求
  }
  next();
});

export default router;
